package com.bignerdranch.android.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import static android.support.v7.recyclerview.R.attr.layoutManager;


/**
 * Created by T540p on 2017/6/7.
 */

public class NewsInterfaceFragment extends Fragment{
    private List<News> newsList=new ArrayList<>();
    private NewsAdapter adapter;
    private Handler handler;
    private ListView lv;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private AppBarLayout mAppBarLayout;
    private RecyclerView mRecyclerView;
    private GridLayoutManager mlayoutManager;
    private boolean isLoading=false;
    private int lastVisibleItemPosition;

    @Override
    public void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
        View v=inflater.inflate(R.layout.news_interface,container,false);
        mAppBarLayout=(AppBarLayout)getActivity().findViewById(R.id.appbar_layout);
        mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh) ;
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mSwipeRefreshLayout.setRefreshing(true);
        mRecyclerView=(RecyclerView)v.findViewById(R.id.news_lv);



        getNews();

        mlayoutManager=new GridLayoutManager(getContext(),2);
        mRecyclerView.setLayoutManager(mlayoutManager);
        adapter=new NewsAdapter(getContext(),newsList);
        mRecyclerView.setAdapter(adapter);
        adapter.setItemClickListener(new MyItemClickListener() {
                                         @Override
                                         public void onItemClick(View view, int position) {
                                             News news=newsList.get(position);
                                             Intent intent=new Intent(getActivity(),NewsDisplayActivity.class);
                                             intent.putExtra("news_url",news.getNewsUrl());
                                             startActivity(intent);
                                         }
                                     }
        );

        handler=new Handler(){
            @Override
            public void handleMessage(Message msg){
                if(msg.what == 1){
                    adapter.notifyDataSetChanged();
                    mSwipeRefreshLayout.setRefreshing(false);
                    adapter.notifyItemChanged(adapter.getItemCount());
                    isLoading=false;
                }
            }
        };



        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getNews();
                //刷新
            }
        });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrolled(RecyclerView recyclerView,int dx, int dy) {
                super.onScrolled(recyclerView,dx,dy);
                lastVisibleItemPosition = mlayoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    if (!isLoading) {
                        isLoading = true;
                        getNews();
                        //加载更多
                    }
                }
            }
        });


        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset >= 0 && !isLoading) {
                    mSwipeRefreshLayout.setEnabled(true);
                } else {
                    mSwipeRefreshLayout.setEnabled(false);
                }
            }
        });

        return v;
    }

    private void getNews(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{

                    //获取人民网/教育/大学专栏7页的数据，网址格式为：http://edu.people.com.cn/GB/227065/index第几页
                    for(int i = 1;i<=7;i++) {
                        Document doc = Jsoup.connect("https://voice.hupu.com/nba/" + Integer.toString(i)).get();
                        Elements titleLinks = doc.select("div.list-hd");    //解析来获取每条新闻的标题与链接地址
                        //Elements descLinks = doc.select("div.list-content");//解析来获取每条新闻的简介
                        Elements timeLinks = doc.select("div.otherInfo");   //解析来获取每条新闻的时间与来源
                        for(int j = 0;j < titleLinks.size();j++){
                            String title = titleLinks.get(j).select("a").text();
                            String uri = titleLinks.get(j).select("a").attr("href");
                            //String desc = descLinks.get(j).select("span").text();
                            String time = timeLinks.get(j).select("span.other-left").select("a").text();
                            News news = new News(title,uri,time);
                            newsList.add(news);
                        }
                    }
                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void refreshNewsList(){

    }

    public void uploadNewsList(){


    }
}
